﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccessLayer;
using System.Web;
using System.IO;

namespace CommonUtils
{
    class ImageDisplayer : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                HttpRequest request = context.Request;
                HttpServerUtility server = context.Server;

                string userName = request.QueryString["userName"];
                System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg;
                string contentType = "image/jpeg" ;
                byte[] myData = UserDAL.GetPictureForUser(userName);

                
                if (myData != null)
                {
                    Stream myStream = new MemoryStream(myData);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(myStream);
                    context.Response.ContentType = contentType;
                    image.Save(context.Response.OutputStream, format);
                }
                else
                {
                    myData = UserDAL.GetPictureForUser("default");
                    Stream myStream = new MemoryStream(myData);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(myStream);
                    context.Response.ContentType = contentType;
                    image.Save(context.Response.OutputStream, format);
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(e, LogStatus.Error, CommonUtilsSettings.Default.ApplicationName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", e);
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}
